package com.draemon.haixiawenti.mvc;

import com.draemon.haixiawenti.constant.ValueConstant;
import com.draemon.haixiawenti.repository.*;
import com.draemon.haixiawenti.sms.holder.SMSHolder;
import com.draemon.haixiawenti.util.DigestUtil;
import com.draemon.haixiawenti.vo.ResponseVO;
import com.draemon.haixiawenti.vo.TieVO;
import com.yangzcp.userpojo.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Created by zhou on 2016/11/13.
 */
@RestController
public class UsersController {

    @Autowired
    private B_base_configRepository b_base_configRepository;

    @Autowired
    private B_saichengRepository b_saichengRepository;

    @Autowired
    private B_saiimgRepository b_saiimgRepository;

    @Autowired
    private B_saiimg_imgRepository b_saiimg_imgRepository;

    @Autowired
    private B_saizhongRepository b_saizhongRepository;

    @Autowired
    private B_saizu_ggRepository b_saizu_ggRepository;

    @Autowired
    private B_dasaiRepository b_dasaiRepository;

    @Autowired
    private B_zhanjiRepository b_zhanjiRepository;

    @Autowired
    private B_saizu_qiuduiRepository b_saizu_qiuduiRepository;

    @Autowired
    private B_qiuduiRepository b_qiuduiRepository;

    @Autowired
    private B_saizuRepository b_saizuRepository;

    @Autowired
    private B_qiuyuanRepository b_qiuyuanRepository;

    @Autowired
    private B_jinqiuRepository b_jinqiuRepository;

    @Autowired
    private B_fapaiRepository b_fapaiRepository;

    @Autowired
    private NewsRepository newsRepository;

    @Autowired
    private AppsRepository appsRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Autowired
    private TieRepository tieRepository;

    @Autowired
    private ShouchangRepository shouchangRepository;

    @Autowired
    private SayRepository sayRepository;

    @Autowired
    private News_SayRepository news_sayRepository;

    @Autowired
    private SMSHolder smsHolder;

    private Integer jinggaotop = 3;

    private String signKey = "sign";

    private String yzmAll = "201711";

    private Map<String, String> yzmcache = new Hashtable<String, String>();

    @RequestMapping(value = "/users/login", method = RequestMethod.POST)
    @ApiOperation("用户登录")
    public ResponseVO<Users> userRegister(@ApiParam("电话号码") @RequestParam("tel") String tel, @ApiParam("短信校验码")  @RequestParam("checkcode") String checkcode) throws ExecutionException {
        ResponseVO<Users> result = new ResponseVO<Users>();
        String s = yzmcache.get(tel);
        if(checkcode.equals(s) || checkcode.equals(yzmAll)){
            Users byTel = usersRepository.findByTel(tel);
            if(byTel == null){
                Users users = new Users();
                users.setGuan_flag(ValueConstant.ZUQIUAIHAOZHE);
                users.setShouchang_count(0);
                users.setJinggao(0);
                users.setJinggao_top(jinggaotop);
                users.setTel(tel);
                users.setSign(UUID.randomUUID().toString());
                users.setName(tel);
                users.setPhoto("avatar.png");
                Users save = usersRepository.save(users);
                result.setData(save);
            }else{
                result.setData(byTel);
            }
        }else{
            result.setStatus(ResponseVO.ERROR);
            result.setMessage("短信验证码错误");
        }
        return result;
    }

    @RequestMapping(value = "/users/register/photo", method = RequestMethod.POST)
    @ApiOperation("用户上传头像")
    public ResponseVO<Users> userRegisterphoto(@ApiParam("头像") @RequestParam("photo") String photo, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) throws ExecutionException {
        ResponseVO<Users> result = new ResponseVO<Users>();
        Users bySign = usersRepository.findBySign(loginSign);
        if(bySign != null){
            bySign.setPhoto(photo);
            usersRepository.save(bySign);
        }else{
            result.setStatus(ResponseVO.ERROR);
            result.setMessage("用户不存在");
        }
        return result;
    }

    @RequestMapping(value = "/users/register/qianming", method = RequestMethod.POST)
    @ApiOperation("用户个性签名")
    public ResponseVO<Users> userRegisterqianming(@ApiParam("个性签名") @RequestParam("qianming") String qianming, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) throws ExecutionException {
        ResponseVO<Users> result = new ResponseVO<Users>();
        Users bySign = usersRepository.findBySign(loginSign);
        if(bySign != null){
            bySign.setQianming(qianming);
            usersRepository.save(bySign);
        }else{
            result.setStatus(ResponseVO.ERROR);
            result.setMessage("用户不存在");
        }
        return result;
    }

    @RequestMapping(value = "/users/register/base", method = RequestMethod.POST)
    @ApiOperation("用户信息完善")
    public ResponseVO<Users> userRegisterbase(@ApiParam("姓名") @RequestParam("name") String name, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) throws ExecutionException {
        ResponseVO<Users> result = new ResponseVO<Users>();
        Users bySign = usersRepository.findBySign(loginSign);
        if(bySign != null){
            bySign.setName(name);
            usersRepository.save(bySign);
        }else{
            result.setStatus(ResponseVO.ERROR);
            result.setMessage("用户不存在");
        }
        return result;
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ApiOperation("用户信息")
    public Users userinfo(@ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        Users one = usersRepository.findBySign(loginSign);
        int i = shouchangRepository.countUserShouchang(loginSign);
        one.setShouchang_count(i);
        return one;
    }

    @RequestMapping(value = "/sign/send/{tel}", method = RequestMethod.POST)
    @ApiOperation("发送验证码")
    public ResponseVO sendSign(@ApiParam("电话号码") @PathVariable("tel") String tel, @ApiParam("加密串：加密规则MD5(\"sign\" + tel) 31b4beadb6286ed9d186f5ed6dbe8b51") @RequestParam("sign") String sign) {
        String resign = DigestUtil.md5(signKey + tel);
        if(resign.equals(sign)){
            String s = smsHolder.sendYZM(tel);
            yzmcache.put(tel, s);
            return new ResponseVO();
        }else{
            throw new RuntimeException("密钥错误");
        }
    }

    @RequestMapping(value = "/sign/{tel}/{checkcode}", method = RequestMethod.GET)
    @ApiOperation("验证码校验")
    public ResponseVO checkSign(@ApiParam("电话号码") @PathVariable("tel") String tel,@ApiParam("验证码, 201711") @PathVariable("checkcode") String checkcode) throws ExecutionException {
        ResponseVO result = new ResponseVO();
        String s = yzmcache.get(tel);
        if(checkcode.equals(s)){
            return result;
        }else{
            result.setStatus(ResponseVO.ERROR);
            result.setMessage("验证码错误");
        }
        return result;
    }

    @RequestMapping(value = "/tie/list", method = RequestMethod.GET)
    @ApiOperation("足球圈帖子列表")
    public Page<TieVO> tieList(@ApiParam("页, 从0开始") @RequestParam("page") int page, @ApiParam("每页数量") @RequestParam("size") int size, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        List<TieVO> reuslt = new ArrayList<TieVO>();
        PageRequest pageRequest = new PageRequest(page, size);
        Page<Tie> ties = tieRepository.findTies(pageRequest);
        for (Tie tie : ties) {
            TieVO tieVO = new TieVO();
            Shouchang cond = shouchangRepository.findCond(tie.getId(), loginSign);
            int i = shouchangRepository.countTieShouchang(tie.getId());
            tie.setShouchang_count(i);
            tieVO.setTie(tie);
            if(cond != null){
                tieVO.setShouchanged(true);
            }else{
                tieVO.setShouchanged(false);
            }
            reuslt.add(tieVO);
        }
        return new PageImpl<TieVO>(reuslt, pageRequest, ties.getTotalElements());
    }

    @RequestMapping(value = "/tie", method = RequestMethod.GET)
     @ApiOperation("足球圈帖子展示")
     public TieVO tie(@ApiParam("帖子ID") @RequestParam("id") Integer id, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        TieVO result = new TieVO();
        Shouchang cond = shouchangRepository.findCond(id, loginSign);
        Tie one = tieRepository.findOne(id);
        if(cond != null){
            result.setShouchanged(true);
        }else{
            result.setShouchanged(false);
        }
        result.setTie(one);
        return result;
    }

    @RequestMapping(value = "/tie", method = RequestMethod.POST)
    @ApiOperation("足球圈发帖")
    public Tie tiesend(@ApiParam("视频链接") @RequestParam(value = "videoUrl", required = false) String videoUrl, @ApiParam("图片url") @RequestParam(value = "img", required = false) String img, @ApiParam("内容") @RequestParam(value = "content", required = false) String content, @ApiParam("视频链接") @RequestParam(value = "locationUrl", required = false) String locationUrl,  @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        Tie tie = new Tie();
        tie.setShouchang_count(0);
        tie.setImg(img);
        tie.setVideo_url(videoUrl);
        tie.setContent(content);
        tie.setLocation_url(locationUrl);
        tie.setRef_users(usersRepository.findBySign(loginSign));
        return tieRepository.save(tie);
    }

    @RequestMapping(value = "/say", method = RequestMethod.GET)
    @ApiOperation("发表评论")
    public ResponseVO<Say> say(@ApiParam("帖子ID") @RequestParam("tieId") Integer tieid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign,@ApiParam("评论内容") @RequestParam("content") String content) {
        ResponseVO<Say> result = new ResponseVO<Say>();
        Say say = new Say();
        say.setContent(content);
        say.setRef_say(tieRepository.findOne(tieid));
        say.setRef_users(usersRepository.findBySign(loginSign));
        sayRepository.save(say);
        result.setData(say);
        return result;
    }

    @RequestMapping(value = "/newssay", method = RequestMethod.GET)
    @ApiOperation("发表新闻评论")
    public ResponseVO<News_say> newssay(@ApiParam("新闻ID") @RequestParam("newsid") Integer newsid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign,@ApiParam("评论内容") @RequestParam("content") String content) {
        ResponseVO<News_say> result = new ResponseVO<News_say>();
        News_say news_say = new News_say();
        news_say.setContent(content);
        news_say.setRef_news_say(newsRepository.findOne(newsid));
        news_say.setRef_users(usersRepository.findBySign(loginSign));
        news_sayRepository.save(news_say);
        result.setData(news_say);
        return result;
    }

    @RequestMapping(value = "/say/list", method = RequestMethod.GET)
    @ApiOperation("帖子评论列表")
    public List<Say> sayList(@ApiParam("帖子ID") @RequestParam("tieId") Integer tieid) {
        return sayRepository.findCond(tieid);
    }

    @RequestMapping(value = "/say/newslist", method = RequestMethod.GET)
    @ApiOperation("新闻评论列表")
    public List<News_say> newssayList(@ApiParam("新闻ID") @RequestParam("newsId") Integer newsId) {
        return news_sayRepository.findCond(newsId);
    }

    @RequestMapping(value = "/shouchang", method = RequestMethod.POST)
    @ApiOperation("收藏")
    public ResponseVO<Shouchang> shouchang(@ApiParam("帖子ID") @RequestParam("tieId") Integer tieid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        ResponseVO responseVO = new ResponseVO();
        Shouchang cond = shouchangRepository.findCond(tieid, loginSign);
        if(cond != null){
            responseVO.setStatus(ResponseVO.ERROR);
            responseVO.setMessage("该用户已收藏");
        }else{
            Shouchang shouchang = new Shouchang();
            shouchang.setRef_users(usersRepository.findBySign(loginSign));
            shouchang.setRef_tie(tieRepository.findOne(tieid));
            shouchangRepository.save(shouchang);
            responseVO.setData(shouchang);
        }
        return responseVO;
    }

    @RequestMapping(value = "/shouchang/delete", method = RequestMethod.POST)
    @ApiOperation("取消收藏")
    public ResponseVO shouchangdelete(@ApiParam("帖子ID") @RequestParam("tieId") Integer tieid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        ResponseVO responseVO = new ResponseVO();
        Shouchang cond = shouchangRepository.findCond(tieid, loginSign);
        if(cond != null){
            shouchangRepository.delete(cond);
        }else{
            responseVO.setStatus(ResponseVO.ERROR);
            responseVO.setMessage("收藏不存在");
        }
        return responseVO;
    }

    @RequestMapping(value = "/users/shouchang/history", method = RequestMethod.GET)
    @ApiOperation("用户点赞历史")
    public Page<TieVO> userShouchangList( @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        List<TieVO> reuslt = new ArrayList<TieVO>();
        PageRequest pageRequest = new PageRequest(0, 100000);
        Page<Tie> ties = tieRepository.findTies(pageRequest);
        for (Tie tie : ties) {
            TieVO tieVO = new TieVO();
            Shouchang cond = shouchangRepository.findCond(tie.getId(), loginSign);
            int i = shouchangRepository.countTieShouchang(tie.getId());
            tie.setShouchang_count(i);
            tieVO.setTie(tie);
            if(cond != null){
                tieVO.setShouchanged(true);
            }else{
                continue;
            }
            reuslt.add(tieVO);
        }
        return new PageImpl<TieVO>(reuslt, pageRequest, ties.getTotalElements());
    }

    @RequestMapping(value = "/users/ties/history", method = RequestMethod.GET)
    @ApiOperation("用户帖子历史")
    public Page<TieVO> userTieList(@ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        List<TieVO> reuslt = new ArrayList<TieVO>();
        PageRequest pageRequest = new PageRequest(0, 1000000);
        Page<Tie> ties = tieRepository.findTies(pageRequest);
        for (Tie tie : ties) {
            if(tie.getRef_users().getSign().equals(loginSign)){
                TieVO tieVO = new TieVO();
                Shouchang cond = shouchangRepository.findCond(tie.getId(), loginSign);
                int i = shouchangRepository.countTieShouchang(tie.getId());
                tie.setShouchang_count(i);
                tieVO.setTie(tie);
                if(cond != null){
                    tieVO.setShouchanged(true);
                }else{
                    tieVO.setShouchanged(false);
                }
                reuslt.add(tieVO);
            }
        }
        return new PageImpl<TieVO>(reuslt, pageRequest, ties.getTotalElements());
    }

    @RequestMapping(value = "/users/ties/delete", method = RequestMethod.DELETE)
    @ApiOperation("删除用户帖子")
    public ResponseVO deleteUsersTie(@ApiParam("帖子ID") @RequestParam("tieid") Integer tieid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        ResponseVO<List<Tie>> responseVO = new ResponseVO();
        Tie tie = tieRepository.getUserTie(loginSign, tieid);
        if(tie != null){
            tieRepository.delete(tie);
        }else{
            responseVO.setStatus(ResponseVO.ERROR);
            responseVO.setMessage("帖子ID不存在：" + tieid);
        }
        return responseVO;
    }

    @RequestMapping(value = "/users/say/delete", method = RequestMethod.DELETE)
    @ApiOperation("删除用户评论")
    public ResponseVO deleteUsersSay(@ApiParam("帖子ID") @RequestParam("sayid") Integer sayid, @ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        ResponseVO<List<Tie>> responseVO = new ResponseVO();
        Say say = sayRepository.getUserSay(loginSign, sayid);
        if(say != null){
            sayRepository.delete(say);
        }else{
            responseVO.setStatus(ResponseVO.ERROR);
            responseVO.setMessage("评论ID不存在：" + say);
        }
        return responseVO;
    }

    @RequestMapping(value = "/users/say/history", method = RequestMethod.GET)
    @ApiOperation("用户评论历史")
    public ResponseVO<List<Say>> userSayList(@ApiParam("登录密钥") @RequestParam("loginSign") String loginSign) {
        ResponseVO<List<Say>> responseVO = new ResponseVO();
        List<Say> cond = sayRepository.findUserSayList(loginSign);
        responseVO.setData(cond);
        return responseVO;
    }

    private ResponseVO reCheckLogin(ResponseVO responseVO, String loginSign){
        Users bySign = usersRepository.findBySign(loginSign);
        if(bySign != null){
            return responseVO;
        }else{
            ResponseVO error = new ResponseVO();
            error.setStatus(ResponseVO.ERROR);
            error.setMessage("登录密钥错误");
            return error;
        }
    }

}
